package com.jiaeda.shiromaster.util;

import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

import javax.annotation.Resource;
import java.util.Set;

@Component
public class JedisUtil {


    private static JedisPool jedisPool = null;

    public static JedisPool getPool() {
        if (jedisPool == null) {
            JedisPoolConfig config = new JedisPoolConfig();
            //控制一个pool可分配多少个jedis实例，通过pool.getResource()来获取；
            //如果赋值为-1，则表示不限制；如果pool已经分配了maxActive个jedis实例，则此时pool的状态为exhausted(耗尽)。
//            config.setMaxTotal(500);
            //控制一个pool最多有多少个状态为idle(空闲的)的jedis实例。
            config.setMaxIdle(5);
            //表示当borrow(引入)一个jedis实例时，最大的等待时间，如果超过等待时间，则直接抛出JedisConnectionException；
//            config.setMaxWaitMillis(1000 * 100);
            //在borrow一个jedis实例时，是否提前进行validate操作；如果为true，则得到的jedis实例均是可用的；
            config.setTestOnBorrow(true);
            jedisPool = new JedisPool(config, "192.168.20.8", 6379);
        }
        return jedisPool;
    }

    private Jedis getResource() {
        getPool();
        return jedisPool.getResource();
    }

    public byte[] set(byte[] key, byte[] value) {
        Jedis jedis = getResource();
        try {
            jedis.set(key, value);
            return value;
        } catch (Exception e) {
            System.out.println(e.getMessage());
        } finally {
            jedis.close();
        }
        return null;
    }

    public void expire(byte[] key, int i) {
        Jedis jedis = getResource();
        try {
            jedis.expire(key, i);
        } catch (Exception e) {
            System.out.println(e.getMessage());
        } finally {
            jedis.close();
        }

    }

    public byte[] get(byte[] key) {
        Jedis jedis = getResource();
        try {
            return jedis.get(key);
        } catch (Exception e) {
            System.out.println(e.getMessage());
        } finally {
            jedis.close();
        }
        return null;
    }

    public void del(byte[] key) {
        Jedis jedis = getResource();
        try {
            jedis.get(key);
        } catch (Exception e) {
            System.out.println(e.getMessage());
        } finally {
            jedis.close();
        }
    }

    public Set<byte[]> keys(String shiro_session_prefix) {
        Jedis jedis = getResource();
        try {
            return jedis.keys((shiro_session_prefix + "*").getBytes());
        } catch (Exception e) {
            System.out.println(e.getMessage());
        } finally {
            jedis.close();
        }
        return null;
    }
}
